import com.gitee.grower.ItemGrower
import com.gitee.grower.ItemGrowerAPI

object Test {

    @JvmStatic
    fun main(args: Array<String>) {
        var i = 3
        val k = (i++)+(i++)+(i++)
        println("k = $k,i = $i")
    }

    val appendAddonLore = "&f&a(&b{0}&a)"

    fun addonIncrease(string: String, value: Double): String {
        val matcher = Matcher.parse(string)
        if (matcher is Matcher.Single) {
            return addonIncrease(string, value, matcher)
        }
        if (matcher is Matcher.Range) {
            return string.replaceFirst(matcher.pos1.parse, addonIncrease(string, value, matcher.pos1))
                .replaceAfterLast(matcher.pos2.parse, addonIncrease(string, value, matcher.pos2))
        }
        return string
    }

    fun addonIncrease(string: String, value: Double, matcher: Matcher.Single): String {
        matcher.extraAmount += value

        return if (matcher.sub.isNotEmpty()) {
            string.replace(matcher.sub.toString(), matcher.extraAmount.toString())
        } else {
            "$string${appendAddonLore.replaceWithOrder(ItemGrowerAPI.toCommonValue(value))}"
        }
    }

    fun String.replaceWithOrder(vararg args: Any): String {
        if (args.isEmpty() || isEmpty()) {
            return this
        }
        val chars = toCharArray()
        val builder = StringBuilder(length)
        var i = 0
        while (i < chars.size) {
            val mark = i
            if (chars[i] == '{') {
                var num = 0
                val alias = StringBuilder()
                while (i + 1 < chars.size && chars[i + 1] != '}') {
                    i++
                    if (Character.isDigit(chars[i]) && alias.isEmpty()) {
                        num *= 10
                        num += chars[i] - '0'
                    } else {
                        alias.append(chars[i])
                    }
                }
                if (i != mark && i + 1 < chars.size && chars[i + 1] == '}') {
                    i++
                    if (alias.isNotEmpty()) {
                        val str = alias.toString()
                        builder.append((args.firstOrNull { it is Pair<*, *> && it.second == str } as? Pair<*, *>)?.first ?: "{$str}")
                    } else {
                        builder.append(args.getOrNull(num) ?: "{$num}")
                    }
                } else {
                    i = mark
                }
            }
            if (mark == i) {
                builder.append(chars[i])
            }
            i++
        }
        return builder.toString()
    }
}